import {Component, Input, OnInit} from '@angular/core';
import {NzModalRef} from "ng-zorro-antd/modal";
import {BarnRole} from "../entity/barn-role";
import {FormControl, FormGroup} from "@angular/forms";
import {RoleInfoService} from "../service/role-info.service";

@Component({
  selector: 'app-role-selection',
  templateUrl: './role-selection.component.html',
  styleUrls: ['./role-selection.component.less']
})
export class RoleSelectionComponent implements OnInit {

  @Input()
  height = 1000

  @Input()
  multi = false

  selected: string[] = []

  validateForm = new FormGroup({
    roleName: new FormControl()
  });
  loading = false
  roles: BarnRole[]
  current = 1;
  pageSize = 20;
  count = 1000;

  constructor(private modal: NzModalRef, private roleService: RoleInfoService) {
  }

  ngOnInit(): void {
    this.search()
  }

  close() {
    this.modal.destroy(this.selected)
  }

  search() {
    const param = this.validateForm.getRawValue();
    this.loading = true
    this.roleService.query(param, this.current, this.pageSize).subscribe(value => {
      this.roles = value.data
      this.current = value.current
      this.count = value.count
      this.loading = false
    }, () => this.loading = false)
  }

  select(pid: string) {
    if (this.multi) {
      const old = this.selected.find(v => v === pid);
      if (old) {
        this.selected = this.selected.filter(v => v !== pid)
      } else {
        this.selected.push(pid)
      }
    } else {
      this.selected = []
      this.selected.push(pid)
    }
  }

  isSelected(pid: string): boolean {
    return !!this.selected.find(v => v === pid)
  }

}
